<template>
  <div class="send-message">
    <textarea type="textarea" id="send-message-input" class="send-message-input" v-model="input" rows="2"></textarea>
    <div class="send-message-fotter flex-2">
      <div style="width: 140px;">
         <el-select v-model="form.model" placeholder="请选择模型" @change="handelchange">
              <el-option v-for="(item, index) in form.models" :key="index" :label="item" :value="item" />
            </el-select>
      </div>
      <div>
        <el-button :disabled="diseble" circle type="primary" @click="start">
          <el-icon v-if="!loading">
            <Upload />
          </el-icon>
          <el-icon class=" is-loading" v-else><Loading /></el-icon>
        </el-button>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { Api } from "@/api/chat";
import { useAppStoreWithOut } from "@/store/modules/app";
import { chatData, StreamEventHandlers } from "@/types";
import { chatMeeages, ConversationGroupListFace } from "@/types/chat.type";
import StreamManager from "@/utils/worker/StreamManager";
import { nextTick, onMounted, ref, defineProps, computed, reactive, watch } from "vue";
import { useChatStoreWithOut } from "@/store/modules/chat";
import dayjs from "dayjs";

import { v4 as uuidv4 } from "uuid";
import { initConversationGroup } from "@/utils";
const appstore = useAppStoreWithOut();
const props = defineProps<{ parentId: number }>();
const chatStore = useChatStoreWithOut();
const emit = defineEmits(["update", "updateUser"]);

const form = reactive({
  models: chatStore.getModels,
  model: chatStore.getCurrentModel
});
const input = ref<string>("");
const loading = ref(false);
let stream: StreamManager;
const uid = ref<string>();

watch(() => chatStore.getModels, (v) => {
  form.models = chatStore.getModels
}, { immediate: true })

watch(() => chatStore.getCurrentModel, (v) => {
  form.model = chatStore.getCurrentModel
}, { immediate: true })

const handelchange = (v: string) => {
chatStore.setCurrentModel(v)
}
const handlers: StreamEventHandlers = {
  onData: function (content: chatData): void {
    const data: chatMeeages = {
      id: 0,
      updateTime: dayjs().unix(),
      createTime: "",
      isDel: 0,
      deleTime: "",
      userID: appstore.getSlefUsetInfo.id,
      conversationID: chatStore.getCurrentConversationGroupId,
      conversationContent: content.content,
      reasoningContent: content.reasoning_content,
      filesURL: "",
      role: "assistant",
      parentId: 0,
      tokens: content.total_tokens,
      thinkingTime: content.thinking_time,
      uuid: uid.value
    };
    emit("update", data);
  },
  onTitleData:(content:ConversationGroupListFace)=>{
    chatStore.setCurrentConversationGroupId(content.id)
    initConversationGroup()
  },
  onError: function (error: Error): void {
    console.log("出错了", error.message);
    loading.value = false
  },
  onEnd: function (): void {
    uid.value = "";
    loading.value = false
    console.log("关闭了");
  },
};
const diseble = computed(() => {
  if (input.value) {
    return false;
  } else {
    return true;
  }
});
const start = () => {
  loading.value = true;
  const api = Api.chatStream;
  const headers = {
    "Content-Type": "application/json",
    Authorization: appstore.getToken,
  };
  const parmas = {
    model: chatStore.getCurrentModel,
    modelId: chatStore.getCurrentModelId,
    userMessage: input.value,
    conversationGroupId: chatStore.getCurrentConversationGroupId,
  };
  stream = new StreamManager(api, parmas, handlers, headers);
  stream.connect();
  uid.value = uuidv4();
  const userdata: chatMeeages = {
    id: 0,
    updateTime: dayjs().unix(),
    createTime: "",
    isDel: 0,
    deleTime: "",
    userID: appstore.getSlefUsetInfo.id,
    conversationID: chatStore.getCurrentConversationGroupId,
    conversationContent: input.value,
    reasoningContent: "",
    filesURL: "",
    role: "user",
    parentId: props.parentId || 0,
    tokens: 0,
    thinkingTime: 0,
    uuid: uuidv4(),
  };
  emit("updateUser", userdata);
  input.value = ""
};
onMounted(async () => {
  await nextTick();
  const textarea = document.getElementById("send-message-input");

  // 输入时调整高度
  textarea.addEventListener("input", function () {
    this.style.height = "auto";
    this.style.height = this.scrollHeight + "px";
  });

  // 初始化时设置正确高度
  setTimeout(() => {
    textarea.style.height = textarea.scrollHeight + "px";
  }, 0);
});
</script>
<style lang="scss" scoped>
.send-message-fotter {
  padding: 0 20px 10px;
}

.send-message-input {
  width: 100%;
  min-height: 40px;
  padding: 10px;
  line-height: 1.5;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow-y: hidden;
  /* 隐藏默认滚动条 */
  resize: none;
  /* 禁用拖动调整 */
  transition: height 0.2s ease;
  /* 允许垂直调整大小 */
  box-sizing: border-box;
  border: none;
  background-color: transparent;
}

textarea:focus {
  outline: none;
  /* 移除默认聚焦轮廓 */
  border: none;
  /* 保持边框与默认一致 */
  box-shadow: none;
  /* 移除可能存在的阴影 */
}

.send-message {
  width: 100%;
  border-radius: 20px;
  border: 1px solid #000;
  overflow: hidden;
  background-color: rgb(243, 244, 246);
}
</style>
